package com.detection.hikvision.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.detection.common.domain.hikvision.accessControlDoControl.AccessControlDoControlResultView;
import com.detection.common.domain.hikvision.accessControlInfo.AccessControlInfoResultView;
import com.detection.common.domain.hikvision.accessControlOnline.AccessControlPageResultView;
import com.detection.common.domain.hikvision.accessControlStates.AccessControlStateResultView;
import com.detection.common.perimeter.hikvision.DeviceStatus;
import com.detection.hikvision.config.CusArtemisConfig;
import com.detection.hikvision.service.AccessControlService;
import com.detection.hikvision.utils.ArtemisApi;
import com.detection.hikvision.utils.HaiKangHttpUtils;
import com.hikvision.artemis.sdk.Client;
import com.hikvision.artemis.sdk.Request;
import com.hikvision.artemis.sdk.Response;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.hikvision.artemis.sdk.constant.Constants;
import com.hikvision.artemis.sdk.enums.Method;
import org.apache.commons.lang3.StringUtils;
import org.junit.platform.commons.logging.Logger;
import org.junit.platform.commons.logging.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;


/**
 * @program: ruoyi
 * @description:
 * @author: 苑福建
 * @create: 2022-10-26 10:51
 **/
@Service
public class AccessControlServiceImpl implements AccessControlService {
    private static final Logger logger = LoggerFactory.getLogger(AccessControlServiceImpl.class);
    @Resource
    private CusArtemisConfig cusArtemisConfig;

    /**
     * 获取门禁设备监控点信息
     * @param regionId 区域
     * @param pageNo 页码
     * @param pageSize 每页查询数量
     * @return
     */
    @Override
    public AccessControlPageResultView getAccessControlList(String regionId, Integer pageNo, Integer pageSize) {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("regionId", regionId);
        jsonBody.put("includeSubNode",1);
        jsonBody.put("pageNo", pageNo);
        jsonBody.put("pageSize", pageSize);
        HaiKangHttpUtils haiKangHttpUtils = new HaiKangHttpUtils();
        String send = haiKangHttpUtils.send(cusArtemisConfig, jsonBody, ArtemisApi.GET_ACS_DEVICE_ONLINE_LIST);
        return !ObjectUtils.isEmpty(send) ? JSON.parseObject(send, AccessControlPageResultView.class) : null;
    }

    /**
     * 获取门禁设备监控点信息
     *
     * @param regionId 区域
     * @param status
     * @param pageNo   页码
     * @param pageSize 每页查询数量
     * @return
     */
    @Override
    public AccessControlPageResultView getAccessControlList(String regionId, String status, Integer pageNo, Integer pageSize) {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("regionId", regionId);
        jsonBody.put("includeSubNode", "1");
        if (StringUtils.isNotBlank(status)) {
            jsonBody.put("status", status);//1.在线。0.离线
        }
        jsonBody.put("pageNo", pageNo);
        jsonBody.put("pageSize", pageSize);
        HaiKangHttpUtils haiKangHttpUtils = new HaiKangHttpUtils();
        String send = haiKangHttpUtils.send(cusArtemisConfig, jsonBody, ArtemisApi.GET_ACS_DEVICE_ONLINE_LIST);
        return !ObjectUtils.isEmpty(send) ? JSON.parseObject(send, AccessControlPageResultView.class) : null;
    }

    /**
     * 获取单个门禁设备信息是指根据指定的门禁设备唯一标识来获取门禁设备信息。
     * @param acsDevIndexCode 门禁设备唯一标识
     * @return
     */
    @Override
    public AccessControlInfoResultView getAccessControlInfo(String acsDevIndexCode) {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("acsDevIndexCode", acsDevIndexCode);

        HaiKangHttpUtils haiKangHttpUtils = new HaiKangHttpUtils();
        String send = haiKangHttpUtils.send(cusArtemisConfig, jsonBody, ArtemisApi.GET_ACS_DEVICE_INFO);
        return !ObjectUtils.isEmpty(send) ? JSON.parseObject(send, AccessControlInfoResultView.class) : null;
    }

    /**
     * 该接口支持门常开、门常闭、门开和门闭四种操作。门常开操作，门会一直处于开状态，不会自动关闭，执行门闭操作，门才会关上；门常闭操作，门会一直处于关毕状态，普通卡刷卡门不会被打开，执行门开操作，门会打开；门开操作，执行门打开动作，超过门打开时间，门会自动关上；门闭操作，执行关门动作，会立即把门关上。
     * 调用该接口，首先要通过获取门禁点资源列表的接口，获取到门禁点唯一编号，然后根据门禁点唯一编号进行反控操作，该接口支持单个和多个门禁点操作，如果所有门禁点反控操作成功，则返回成功，其他情况都返回失败，在失败的情况下，会按每个门禁点返回对应的错误。
     * @param acsDevIndexCodes 门禁设备唯一标识，最大支持10个门禁设备。acsDevIndexCode
     * @param controlType 0-常开  1-门闭 2-门开  3-常闭
     * @return
     */
    @Override
    public AccessControlDoControlResultView getAccessControlDoControl(String[] acsDevIndexCodes, int controlType) {
        if(!Objects.isNull(acsDevIndexCodes)){
            //通过门禁设备获取门禁点列表   /api/resource/v1/acsDoor/advance/acsDoorList
            HaiKangHttpUtils haiKangHttpUtils = new HaiKangHttpUtils();
            List<String > doorIndexCodes =new ArrayList<>();
            for(String deviceIndex:acsDevIndexCodes){
                JSONObject jsonBody = new JSONObject();
                jsonBody.put("pageNo", 1);
                jsonBody.put("pageSize", 10);
                jsonBody.put("acsDevIndexCode", deviceIndex);
                String send = haiKangHttpUtils.send(cusArtemisConfig, jsonBody, ArtemisApi.GET_ACS_Door_BY_DEVICE);

                JSONObject result = JSON.parseObject(send);
                JSONObject data =result.getJSONObject("data");
                System.out.println(send);
                JSONArray list= data.getJSONArray("list");
                if(list.size()>0){
                    doorIndexCodes.add(list.getJSONObject(0).getString("doorIndexCode"));
                }
            }
            JSONObject jsonBody = new JSONObject();
            jsonBody.put("doorIndexCodes", doorIndexCodes.toArray());
            jsonBody.put("controlType", controlType);
            String send = haiKangHttpUtils.send(cusArtemisConfig, jsonBody, ArtemisApi.GET_ACS_DEVICE_DOCONTROL);
            return !ObjectUtils.isEmpty(send) ? JSON.parseObject(send, AccessControlDoControlResultView.class) : null;
        }else {
            return null;
        }
    }

    @Override
    public AccessControlStateResultView getAccessControlStates(String[] doorIndexCodes) {
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("doorIndexCodes", doorIndexCodes);
        HaiKangHttpUtils haiKangHttpUtils = new HaiKangHttpUtils();
        String send = haiKangHttpUtils.send(cusArtemisConfig, jsonBody, ArtemisApi.GET_ACS_DEVICE_DOOR_STATES);
        return !ObjectUtils.isEmpty(send) ? JSON.parseObject(send, AccessControlStateResultView.class) : null;
    }

    @Override
    public HashMap<String, String> getAccessControlAcsDoorList() {
        //通过门禁设备获取门禁点列表   /api/resource/v1/acsDoor/advance/acsDoorList
        HaiKangHttpUtils haiKangHttpUtils = new HaiKangHttpUtils();
        HashMap<String, String> objectObjectHashMap = new HashMap<>();
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 100);
        String send = haiKangHttpUtils.send(cusArtemisConfig, jsonBody, ArtemisApi.GET_ACS_Door_BY_DEVICE);
        JSONObject result = JSON.parseObject(send);
        JSONObject data =result.getJSONObject("data");
        System.out.println(send);
        JSONArray list= data.getJSONArray("list");
        if(list.size()>0){
            for (int i = 0; i <list.size() ; i++) {
                objectObjectHashMap.put(list.getJSONObject(i).getString("acsDevIndexCode"),list.getJSONObject(i).getString("doorIndexCode"));
            }
        }
        return objectObjectHashMap;
    }

    @Override
    public AccessControlStateResultView getAllAccessControlStates() {
        JSONObject jsonBody = new JSONObject();
        HaiKangHttpUtils haiKangHttpUtils = new HaiKangHttpUtils();
        String send = haiKangHttpUtils.send(cusArtemisConfig, jsonBody, ArtemisApi.GET_ACS_DEVICE_DOOR_STATES);
        return !ObjectUtils.isEmpty(send) ? JSON.parseObject(send, AccessControlStateResultView.class) : null;
    }

    /**
     * 获取门禁图片地址
     *
     * @param svrIndexCode
     * @param picUri
     * @return
     */
    @Override
    public String getPicUrl(String svrIndexCode, String picUri) {
        HaiKangHttpUtils haiKangHttpUtils = new HaiKangHttpUtils();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("svrIndexCode",svrIndexCode);
        jsonObject.put("picUri",picUri);



        ArtemisConfig.host = cusArtemisConfig.getHost(); // 平台的ip端口
        ArtemisConfig.appKey = cusArtemisConfig.getAppKey();  // 密钥appkey
        ArtemisConfig.appSecret = cusArtemisConfig.getAppSecret();// 密钥appSecret

        /**
         * STEP2：设置OpenAPI接口的上下文
         */
        final String ARTEMIS_PATH = cusArtemisConfig.getArtemisPath();
//        final String previewURLsApi = ARTEMIS_PATH + "/api/irds/v2/region/nodesByParams";
        final String previewURLsApi = ARTEMIS_PATH + ArtemisApi.GET_ACS_EVENT_PIC_URL.getPath();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put(cusArtemisConfig.getTransferProtocol() + "://", previewURLsApi);//根据现场环境部署确认是http还是https
            }
        };

//        String send = haiKangHttpUtils.send(cusArtemisConfig, jsonObject, ArtemisApi.GET_ACS_EVENT_PIC_URL);
//        if (StringUtils.isNotEmpty(send)) {
//            PicUrlView view = JSON.parseObject(send, PicUrlView.class);
//            if(view != null && view.success()){
//                return view.getData();
//            }else {
//                return null;
//            }
//        }

        String httpSchema = (String)path.keySet().toArray()[0];
        if (httpSchema != null && !StringUtils.isEmpty(httpSchema)) {
            String redirectUrl="";
            try {
                Map<String, String> headers = new HashMap();
                headers.put("Accept", "*/*");
                headers.put("Content-Type", "application/json");

                Request request = new Request(Method.POST_STRING, httpSchema + ArtemisConfig.host, (String)path.get(httpSchema), ArtemisConfig.appKey, ArtemisConfig.appSecret, Constants.DEFAULT_TIMEOUT);
                request.setHeaders(headers);
                request.setStringBody(jsonObject.toJSONString());
                Response response = Client.execute(request);
                redirectUrl = response.getHeader("Location");
            } catch (Exception var11) {
//				logger.error("the Artemis PostString Request is failed[doPostStringArtemis]", var11);
            }
            //重定向后的url
            return redirectUrl;
        } else {
            throw new RuntimeException("http和https参数错误httpSchema: " + httpSchema);
        }
    }

    /**
     * 获取在线门禁数
     *
     * @param regionCode
     * @return
     */
    @Override
    public int countOnLineDoorControl(String regionCode) {
        AccessControlPageResultView accessControlList = getAccessControlList(regionCode, DeviceStatus.ONLINE.getStatus(), 1, 1);
        return null != accessControlList && accessControlList.success() ? accessControlList.getData().getTotal() : 0;
    }

    /**
     * 获取离线门禁数
     *
     * @param regionCode
     * @return
     */
    @Override
    public int countOffLineDoorControl(String regionCode) {
        AccessControlPageResultView accessControlList = getAccessControlList(regionCode, DeviceStatus.OFFLINE.getStatus(), 1, 1);
        return null != accessControlList && accessControlList.success() ? accessControlList.getData().getTotal() : 0;
    }
}
